from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Profile
from .forms import ProfileForm, SignUpForm
from core.models import SiteInfo

class SignUpView(CreateView):
    """用户注册视图"""
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'accounts/signup.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_info'] = SiteInfo.get_site_info()
        return context
    
    def form_valid(self, form):
        messages.success(self.request, '账户创建成功，现在您可以登录了。')
        return super().form_valid(form)

@login_required
def profile_view(request):
    """用户资料视图"""
    user = request.user
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=user.profile)
        if form.is_valid():
            form.save()
            messages.success(request, '个人资料更新成功。')
            return redirect('accounts:profile')
    else:
        form = ProfileForm(instance=user.profile)
    
    return render(request, 'accounts/profile.html', {
        'form': form,
        'site_info': SiteInfo.get_site_info()
    })
